package com.chagee.store.operation.server.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chagee.base.exception.SoaException;
import com.chagee.base.utils.SoaResponse;
import com.chagee.base.utils.SoaUtil;
import com.chagee.scm.api.supplier.request.QuerySupplierRequestBo;
import com.chagee.scm.api.supplier.response.SupplierSimpleInfoBO;
import com.chagee.scm.api.supplier.service.SupplierServiceApi;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.entity.WorkOrderReceiverDO;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderReceiverMapper;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.model.bo.StoreInfoBO;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author : hk
 * @Date : 2024/10/25
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class RefreshSupplierNoHandler {

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private WorkOrderBaseService workOrderBaseService;
	@Resource
	private WorkOrderReceiverMapper workOrderReceiverMapper;

	/*@Resource
	private ScmThirdService scmThirdService;*/
	@Resource
	private SupplierServiceApi supplierServiceApi;

	/**
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("refreshSupplierNoHandler")
	public ReturnT<String> refreshSupplierNoHandler(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("刷新供应商编码定时任务开始,traceId :{}", span.getTraceId());
		try {

			int startIndex = 0;
			while (true) {
				log.info("start_index " + startIndex);
				LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(WorkOrderDO::getDeleteFlag,NumberUtils.INTEGER_ZERO);
				queryWrapper.gt(WorkOrderDO::getId, startIndex);
				queryWrapper.orderByAsc(WorkOrderDO::getId);
				queryWrapper.last("limit 200");
				List<WorkOrderDO> workOrderDOList = workOrderMapper.selectList(queryWrapper);
				if (CollectionUtils.isEmpty(workOrderDOList)) {
					break;
				}
				List<String> orderNoList = workOrderDOList.stream().map(WorkOrderDO::getWorkOrderNumber).collect(Collectors.toList());
				log.info("orderNoList: {}" , JSONObject.toJSONString(orderNoList));
				LambdaQueryWrapper<WorkOrderReceiverDO> doLambdaQueryWrapper= new LambdaQueryWrapper<>();
				doLambdaQueryWrapper.in(WorkOrderReceiverDO::getWorkOrderNumber, orderNoList);
				doLambdaQueryWrapper.eq(WorkOrderReceiverDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
				List<WorkOrderReceiverDO> workOrderReceiverDOS = workOrderReceiverMapper.selectList(doLambdaQueryWrapper);

				Map<String, List<WorkOrderReceiverDO>> listMap = new HashMap<>();
				Map<Long, String> stringMap = new HashMap<>();
				if (CollectionUtils.isNotEmpty(workOrderReceiverDOS)) {
					listMap = workOrderReceiverDOS.stream().collect(Collectors.groupingBy(WorkOrderReceiverDO::getWorkOrderNumber));
					List<Long> supplierIds = workOrderReceiverDOS.stream().map(WorkOrderReceiverDO::getSupplierId).distinct().collect(Collectors.toList());
					log.info("refreshSupplierNoHandler_supplierIds: {}" , JSONObject.toJSONString(supplierIds));
					QuerySupplierRequestBo bo = new QuerySupplierRequestBo();
					bo.setIds(supplierIds);
					//List<SupplierSimpleInfoBO> supplierSimpleInfoBOS = scmThirdService.querySupplierInfoByIds(bo);
					SoaResponse<List<SupplierSimpleInfoBO>, SoaException> response = supplierServiceApi.querySupplierInfoByIds(bo);
					log.info("refreshSupplierNoHandler_querySupplierInfoByIds: {}" , JSONObject.toJSONString(response));
					List<SupplierSimpleInfoBO> supplierSimpleInfoBOS = SoaUtil.unpack(response);
					if (CollectionUtils.isNotEmpty(supplierSimpleInfoBOS)) {
						stringMap = supplierSimpleInfoBOS.stream().collect(Collectors.toMap(SupplierSimpleInfoBO::getSupplierBaseId, SupplierSimpleInfoBO::getCode, (s1, s2) -> s1));
					}
				}

				for (WorkOrderDO workOrderDO : workOrderDOList) {
					try {
						List<WorkOrderReceiverDO> workOrderReceiverDOS1 = listMap.get(workOrderDO.getWorkOrderNumber());
						if (CollectionUtils.isEmpty(workOrderReceiverDOS1)) {
							continue;
						}
						WorkOrderReceiverDO workOrderReceiverDO = workOrderReceiverDOS1.get(0);
						String code = stringMap.get(workOrderReceiverDO.getSupplierId());
						if (StringUtils.isNotEmpty(code)) {
							workOrderDO.setSupplierNo(code);
							workOrderBaseService.updateRefreshSupplierNo(workOrderDO);
						}else {
							log.error("工单有供应商接单根据id查询供应商编码为空:工单号 : {}", workOrderDO.getWorkOrderNumber());
						}
					} catch (Exception e) {
						log.error("刷新供应商编码定时任务异常:工单号 : {}, storeId:{}, startIndex:{} 异常信息 : {}", workOrderDO.getWorkOrderNumber(), workOrderDO.getStoreCode(),startIndex, e.getMessage());
					}
				}
				startIndex = Math.toIntExact(workOrderDOList.stream().map(WorkOrderDO::getId).max(Comparator.naturalOrder()).orElse(0L));

			}
		} catch (Exception e) {
			XxlJobLogger.log("刷新供应商编码定时任务异常，异常信息:{}", e.toString());
			log.error("刷新供应商编码定时任务异常 => param : {} => 异常信息 : {}", param, e.toString());
		}
		XxlJobLogger.log("刷新供应商编码定时任务结束，traceId :{},共耗时:{}", span.getTraceId(), timer.intervalRestart());
		return ReturnT.SUCCESS;
	}









}
